/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yutel.wuzi.action;

import com.yutel.wuzi.entities.Chess;
import com.yutel.wuzi.entities.ChessPad;
import java.util.Vector;

/**
 *
 * @author yuanyajun
 */
public class Control {

    static private Control control;
    private ChessPad chessPad;
    private Vector step;
    private boolean gameOver;
    private String gameMessage;

    public String getGameMessage() {
        return gameMessage;
    }

    public void setGameMessage(String gameMessage) {
        this.gameMessage = gameMessage;
    }

    private Control() {
        this.step = new Vector();
    }

    static public Control getIntance() {
        if (control == null) {
            control = new Control();
            control.gameOver = false;
            control.gameMessage = "游戏开始：黑方先走";
        }
        return control;
    }

    public ChessPad getChessPad() {
        if (chessPad == null) {
            chessPad = new ChessPad();
            return chessPad;
        } else {
            return chessPad;
        }
    }

    public boolean pressChess() {
        if (gameOver) {
            return false;
        }
        Chess chess = chessPad.addChess();
        if (step.isEmpty()) {
            chess.setBlack(true);
            gameMessage = "请白方下棋";
            step.addElement(chess);
        } else {
            if (!step.contains(chess)) {
                Chess last = (Chess) step.lastElement();
                chess.setBlack(!last.isBlack());
                if (chess.isBlack()) {
                    gameMessage = "请白方下棋";
                } else {
                    gameMessage = "请黑方下棋";
                }
                step.addElement(chess);
                if (isWin()) {
                    gameOver = true;
                    if (chess.isBlack()) {
                        gameMessage = "游戏结束：黑方赢";
                    } else {
                        gameMessage = "游戏结束：白方赢";
                    }
                }
            }
        }
        return gameOver;

    }

    public void undoChess() {
        if (step.size() > 0) {
            Chess last = (Chess) step.lastElement();
            step.removeElementAt(step.size() - 1);
            if(last.isBlack()){
                gameMessage = "黑方悔棋，请黑方下棋";
            }else {
                gameMessage = "白方悔棋，请白方下棋";
            }
        }
        
        gameOver = false;
    }

    public void newGame() {
        gameMessage = "游戏开始：黑方先走";
        step.removeAllElements();
        gameOver = false;
    }

    public void showMessage() {
        chessPad.drawMessage(gameMessage);
    }

    public Vector getChesses() {
        return step;
    }

    public boolean isWin() {
        return new Calculate().isWin(step);
    }
}
